
package com.carworld.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.carworld.config.BaseController;
import com.carworld.config.UserInter;
import com.carworld.model.ShopOrder;
import com.carworld.model.ShopRecord;
import com.carworld.model.SysUser;
import com.carworld.utils.DateUtils;
import com.carworld.utils.weixin.HttpUtil;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;

public class OrderController extends BaseController {

	/**
	 * 查询待支付、已支付订单列表
	 */
	public void myOrderList() {
		String orderStatus = getPara("orderStatus");
		String userId = getUserCookie();
		JSONObject jsonObject = getJsonObject();
		List<Record> shopOrder = ShopOrder.dao.getJsonPage(userId, orderStatus);
		String orderId = null;
		for (int i = 0; i < shopOrder.size(); i++) {
			orderId = String.valueOf(shopOrder.get(i).getStr("shop_order_id"));
			shopOrder.get(i).set("shopRecord", ShopRecord.dao.getJsonPage(orderId, 1, 10).getList());
		}
		jsonObject.put("shopOrder", shopOrder);
		renderJson(jsonObject);
	}

	/**
	 * 查看全部订单
	 */
	public void myAllOrderList() {
		String userId = getUserCookie();
		JSONObject jsonObject = getJsonObject();
		List<Record> shopOrder = ShopOrder.dao.getAllOrder(userId);
		String orderId = null;
		for (int i = 0; i < shopOrder.size(); i++) {
			orderId = String.valueOf(shopOrder.get(i).getStr("shop_order_id"));
			shopOrder.get(i).set("shopRecord", ShopRecord.dao.getJsonPage(orderId, 1, 5).getList());
		}
		jsonObject.put("shopOrder", shopOrder);
		renderJson(jsonObject);
	}

	/**
	 * 查询订单详情
	 */
	public void myOrderDetail() {
		String orderId = getPara("orderId");
		renderPageJson(ShopRecord.dao.getJsonPage(orderId, 1, 10));
	}

	/**
	 * 查看待打印订单
	 */
	public void pendingOrder() {
		String orderId = getPara("orderId");
		renderPageJson(ShopRecord.dao.getJsonPage(orderId, 1, 10));
	}

	/**
	 * 顾客下单点菜
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@Before(UserInter.class)
	public void customerOrder() throws UnsupportedEncodingException {
		String shopId = getPara("shopId");
		String userId = getUserCookie();
		SysUser user = SysUser.dao.findByIdInCache(getUserCookie());
		String orderUrl = "http://food.3kkk.xyz/xsza/index1.html?" + shopId + "?" + userId + "?"
				+ URLEncoder.encode(user.getUserNickname(), "UTF-8") + "?" + user.getCarBrand();
		System.out.println("url---->" + orderUrl);
		redirect(orderUrl);
	}

	/**
	 * 查看外卖订单详情 6.1
	 */
	public void takeoutOrderInfo() {
		String userId = getUserCookie();
		// String userId = "6ade78ca6c9245f7847cb90c22a9d645";
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("user", SysUser.dao.findByIdInCache(userId));
		jsonObject.put("order", ShopOrder.dao.getLatestOrder(userId));
		renderJson(jsonObject);
	}

	/**
	 * 补充外卖订单信息
	 */
	public void supplyOrderInfo() {
		String userId = getUserCookie();
		String name = getPara("name");
		String mobile = getPara("mobile");
		String adress = getPara("adress");
		String district = getPara("district");
		String remarks = getPara("remarks");
		String status = "failure";
		ShopOrder order = ShopOrder.dao.getLatestOrder(userId);
		if (order != null && 1 != order.getShopOrderStatus()) {
			order.setShopOrderName(name);
			order.setShopOrderPhone(mobile);
			order.setShopOrderCartype(adress);
			order.setShopOrderRemarks(remarks);
			order.setShopOrderCarbrand(district);
			order.update();
			status = "success";
			System.out.println("订单信息补充完成");
		} else {
			System.out.println("该订单无效");
		}
		renderText(status);
	}

	
	//发送分红通知
	public void dividendNotify() {
		String userId = getUserCookie();
		ShopOrder shopOrder = ShopOrder.dao.getdividendNotifyOrder(userId);
		if (shopOrder == null || shopOrder.getShopOrderStatus() != 1) {
			System.out.println("没有可发送分红通知的订单");
			return;
		} else {
			System.out.println("进入通知分红方法");
		}
			
		String orderId = String.valueOf(shopOrder.getShopOrderId());
		ShopOrder order = ShopOrder.dao.findOrderInfo(orderId);

		if (order == null || order.getShopOrderStatus() != 1) {
			System.out.println("订单未支付或不存在，不用查询分红");
			return;
		}
		if (order.getShopOrderStatus() == 1 && order.getShopOrderIsprint() == 2 && order.getShopOrderNotify() == 1) {

			// 获取消费客户信息
			SysUser user = SysUser.dao.findByIdInCache(order.getShopOrderUser());
			// 获取分红股东openId
			String shareholderIdOpenId = SysUser.dao.findByIdInCache(user.getUserOfShareholder()).getUserOpenid();
			Boolean isdividend = false;
			String dividendSumOfShareholder = null; // 调取查询分红的API
			long start, end;
			start = System.currentTimeMillis();
			String URL = "http://47.92.137.225/carWorld/doOrderCount?id=" + orderId;
			String dividendContent = null;
			try {
				dividendContent = HttpUtil.getContentFromUrl(URL);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (dividendContent != null) {
				JSONObject json = JSONObject.parseObject(dividendContent);
				System.out.println("json:" + json.toString());
				dividendSumOfShareholder = String.valueOf(json.getJSONObject("body").get("dividendGDTotal"));
				if (dividendSumOfShareholder != null) {
					isdividend = true;
				} else {
					System.out.println("暂时没有分红");
				}
				System.out.println("dividend:" + dividendSumOfShareholder);
			}
			System.out.println("isdividend--》" + isdividend);
			end = System.currentTimeMillis();
			System.out.println("start time:" + start + "; end time:" + end + "; Run Time:" + (end - start) + "(ms)");

			// 通知股东分红收入
			if (null != shareholderIdOpenId) {
				ApiResult apiResult = TemplateMsgApi.send(TemplateData.New().setTouser(shareholderIdOpenId)
						.setTemplate_id("kDim1M1Hw-uNUWP9LVvRwLz-aEnDKNybd7t5AJZ8kG0") // 收益到账通知模板id
						.setUrl("http://food.3kkk.xyz/carworld_weixin/pages/page_dividendList.html")
						.add("first", "新的分红收益消息提示：\n").add("keyword1", dividendSumOfShareholder + "元", "#173177")
						.add("keyword2", "来自【" + user.getName() + "】的消费", "#173177")
						.add("keyword3", DateUtils.getCurrentTime(new Date()) + "\n", "#173177")
						.add("remark", "推广分红暂不支持查看单笔详情，后续开放。每周以excel统计数据为准", "#173177").build());
				System.out.println("通知推广专员模板消息结果：" + apiResult.getJson());
			}

			order.setShopOrderNotify(2);
			order.update();
			
		} else {
			System.out.println("订单未完成打印状态，返回null");
		}

	}
	
		//来自分红系统发送分红通知 
		public void dividendNotifyFromSystem() {
		    String orderId = getPara("orderId");
		    ShopOrder order = ShopOrder.dao.findOrderInfo(orderId);
		    if (order == null) {
				System.out.println("订单不存在");
				return;
			}
		    
			ShopOrder shopOrder = ShopOrder.dao.getdividendNotifyOrder(order.getShopOrderUser());
			if (shopOrder == null || shopOrder.getShopOrderStatus() != 1) {
				System.out.println("没有可发送分红通知的订单");
				return;
			} else {
				System.out.println("进入通知分红方法");
			}

			if (order == null || order.getShopOrderStatus() != 1) {
				System.out.println("订单未支付或不存在，不用查询分红");
				return;
			}
			if (order.getShopOrderStatus() == 1 && order.getShopOrderIsprint() == 2 && order.getShopOrderNotify() == 1) {

				// 获取消费客户信息
				SysUser user = SysUser.dao.findByIdInCache(order.getShopOrderUser());
				// 获取分红股东openId
				String shareholderIdOpenId = SysUser.dao.findByIdInCache(user.getUserOfShareholder()).getUserOpenid();
				Boolean isdividend = false;
				String dividendSumOfShareholder = null; // 调取查询分红的API
				long start, end;
				start = System.currentTimeMillis();
				String URL = "http://47.92.137.225/carWorld/doOrderCount?id=" + orderId;
				String dividendContent = null;
				try {
					dividendContent = HttpUtil.getContentFromUrl(URL);
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (dividendContent != null) {
					JSONObject json = JSONObject.parseObject(dividendContent);
					System.out.println("json:" + json.toString());
					dividendSumOfShareholder = String.valueOf(json.getJSONObject("body").get("dividendGDTotal"));
					if (dividendSumOfShareholder != null) {
						isdividend = true;
					} else {
						System.out.println("暂时没有分红");
					}
					System.out.println("dividend:" + dividendSumOfShareholder);
				}
				System.out.println("isdividend--》" + isdividend);
				end = System.currentTimeMillis();
				System.out.println("start time:" + start + "; end time:" + end + "; Run Time:" + (end - start) + "(ms)");

				// 通知股东分红收入
				if (null != shareholderIdOpenId) {
					ApiResult apiResult = TemplateMsgApi.send(TemplateData.New().setTouser(shareholderIdOpenId)
							.setTemplate_id("kDim1M1Hw-uNUWP9LVvRwLz-aEnDKNybd7t5AJZ8kG0") // 收益到账通知模板id
							.setUrl("http://food.3kkk.xyz/carworld_weixin/pages/page_dividendList.html")
							.add("first", "新的分红收益消息提示：\n").add("keyword1", dividendSumOfShareholder + "元", "#173177")
							.add("keyword2", "来自【" + user.getName() + "】的消费", "#173177")
							.add("keyword3", DateUtils.getCurrentTime(new Date()) + "\n", "#173177")
							.add("remark", "推广分红暂不支持查看单笔详情，后续开放。每周以excel统计数据为准", "#173177").build());
					System.out.println("通知推广专员模板消息结果：" + apiResult.getJson());
				}
				order.setShopOrderNotify(2);
				order.update();
				
			} else {
				System.out.println("订单未完成打印状态，返回null");
			}

		}
	
	
	

}

